<template>
  <v-layout type="main">
    <div class="detail-layout">
      <el-form class="form myself-form alick-add-form" :rules="rules" ref="form" :model="addForm" label-position="right"
        label-width="120px">
        <h3 class="add-alike-title">基本信息</h3>
        <el-form-item label="名称" class="container" prop="name">
          <el-input size="small" placeholder="请输入名称" v-model.trim="addForm.name" maxlength="40"></el-input>
        </el-form-item>
        <!-- <el-form-item label="描述" class="container" prop="description"> -->
        <el-form-item label="描述" class="container">
          <el-input placeholder="请输入描述" show-word-limit :rows="2" v-model="addForm.description"
            type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="资源配置" class="container" prop="product_id">
          <el-select size="small" class="long-input" v-model="addForm.product_id" placeholder="请选择">
            <el-option v-for="item in productMap" :key="item.id" :label="item.name" :value="item.id - 0"
              :disabled="item.disabled">
              <span style="float: left">{{ item.name }}</span>
              <!-- <strong style="float: right;font-size: 12px">{{ (item.price * 6000) / 100 }}元/小时</strong> -->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="环境" prop="image_id">
          <el-radio-group v-model="addForm.image_roadio" @change="getImages" size="small">
            <el-radio-button label='2'>公开的</el-radio-button>
            <el-radio-button label='1'>共享的</el-radio-button>
            <el-radio-button label='0'>我的</el-radio-button>
          </el-radio-group>

          <div class="user-defined">
            <el-radio-group v-model="addForm.engine" @change="getImages" size="small">
              <el-radio-button label='2'>Pytorch</el-radio-button>
              <el-radio-button label='1'>TensorFlow</el-radio-button>
              <el-radio-button label='3'>其他</el-radio-button>
            </el-radio-group>
          </div>
          <div class="user-defined">
            <!-- multiple -->
            <el-select size="small" class="long-input" v-model="addForm.image_id" @change="extendPortHandler"
              placeholder="请选择">
              <el-option v-for="item in imageMap" :key="item.id" :label="item.name" :value="item.id - 0">
                <!-- <el-tooltip v-if="addForm.image_roadio == 0" class="item" effect="dark" :content="item.description" placement="top">
                    <i class="el-icon-question question"></i>
                  </el-tooltip> -->
                {{ item.name }}
                <!-- <span style="float: left"></span> -->
                <!-- <span style="float: right; color: #8492a6; font-size: 12px">版本：{{ item.version }}</span> -->
              </el-option>
            </el-select>
          </div>

        </el-form-item>

        <!-- <div class="node-module">
          <el-form-item label="环境" prop="mainNodeImageId">
            <div>
              <el-radio-group v-model="addForm.visibility"
                @change="changeMasterEngine(mainNode.visibility, mainNode.engine)" size="small">
                <el-radio-button label='2'>公开的</el-radio-button>
                <el-radio-button label='1'>共享的</el-radio-button>
                <el-radio-button label='0'>我的</el-radio-button>
              </el-radio-group>
            </div>
            <el-radio-group v-model="mainNode.engine"
              @change="changeMasterEngine(mainNode.visibility, mainNode.engine)" size="small">
              <el-radio-button label='2'>Pytorch</el-radio-button>
              <el-radio-button label='1'>TensorFlow</el-radio-button>
              <el-radio-button label='3'>其他</el-radio-button>
            </el-radio-group>
            <div class="select">
              <el-select size="mini" v-model="mainNode.image_id" prop="main_image_id" class="full-extent-select">
                <el-option v-for="item in mainNode.imageOptions" :value="item.id" :label="item.name" :key="item.id">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="资源组" prop="mainProduct">
            <el-select size="mini" v-model="mainNode.product_id" prop="main_product" class="full-extent-select">
              <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div> -->
        <el-form-item label=" " class="btns">
          <!-- <el-button @click="reset">重置</el-button> -->
          <el-button type="primary" @click="submitReject">确认</el-button>
        </el-form-item>
      </el-form>
    </div>
  </v-layout>
</template>

<script>
import { getAllImages } from '@/api/image'
import { getAllProducts } from '@/api/product'
import { addCanvas, putCanvas, getCanvasDetail } from '@/api/dag'

export default {
  data() {
    let validatorimage_id = (rule, val, callback) => {
      // console.log(rule, val)
      if (!this.addForm.image_id) {
        callback(new Error('请选择环境'))
      } else {
        callback()
      }
    }
    let validatorproduct_id = (rule, val, callback) => {
      if (!this.addForm.distributed && !this.addForm.product_id) {
        callback(new Error('请选择资源配置'))
      } else {
        callback()
      }
    }
    return {
      isShowDialog: false,
      fileDone: true,
      isShow: false,
      imageMap: [],
      productMap: [],
      slaveProductMap: [],
      addForm: {
        image_roadio: '2',
        engine: '2',
        port: '',
        ds_roadio: '0',
        is_webide: this.$route.query.is_webide === '3' ? true : false,
        // tensorboard: 1,
        name: '',
        id: '',
        sstore_num: '5',
        image_id: '',
        distributed: false,
        projectId: this.$route.query.id,
        product_id: '',
        slave_list: [],
        port_list: [{ key: '10000' }]
      },
      resetAddForm: {},
      parentVersion: '-',
      taskParent: {},
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 40, message: '最多可输入40字', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' },
        ],
        image_id: [
          { required: true, validator: validatorimage_id, trigger: 'change' },
        ],
        product_id: [
          { required: true, validator: validatorproduct_id, trigger: 'change' },
        ],
      },
      // todoName: '新增',
      port_list: [{ key: '10000' }]//调试端口
    };
  },
  methods: {
    // async getSlaveProducts (noClear) {
    //   let data = data = {
    //     product_type: '1',
    //   }
    //   let res = await getAllProducts(data)
    //   this.slaveProductMap = res.data
    //   if (noClear != 'noClear') {
    //     this.slave_listTemp.product_id = ''
    //   }
    // },
    async getProducts(isUserHandle) {
      let data = {
        product_type: '1'
      }
      let res = await getAllProducts(data)
      // this.addForm.product_id = ''
      this.productMap = res.data
      if (!isUserHandle) {
        this.getImages()
        // this.getSlaveProducts()
      }
    },
    async getImages(isUserHandle, noClear) {
      // visibility: 
      // 2
      // engine: 
      // 2
      // type: 
      // 1
      let data = {
        type: 1,
        visibility: this.addForm.image_roadio
      }
      if (this.addForm.image_roadio === '1') {
        // data.projectId = this.$route.query.id
      } else {
        data.engine = this.addForm.engine
      }
      let res = await getAllImages(data)
      if (noClear !== 'noClear') {
        this.addForm.image_id = ''
        this.addForm.port = ''
      }
      this.imageMap = res.data
    },
    async getImagesSlave(i, noClear) {
      let data = {
        imageType: 'notebook',
        visibility: this.addForm.slave_list[i].image_roadio
      }
      if (this.addForm.slave_list[i].image_roadio != '1') {
        data.engine = this.addForm.slave_list[i].engine
      } else {
        data.engine = null
      }
      // let res = await getAllImages(data)
      console.log(noClear)
      if (noClear !== 'noClear') {
        this.addForm.slave_list[i].image_id = ''
        this.addForm = JSON.parse(JSON.stringify(this.addForm))
      }
      this.addForm.slave_list[i].imageMapSlave = await getAllImages(data)
      this.addForm = JSON.parse(JSON.stringify(this.addForm))
    },
    async handleRunType() {
      if (this.addForm.distributed && (!this.addForm.slave_list || this.addForm.slave_list.length == 0)) {
        this.addForm.slave_list = [
          {
            product_id: '',
            image_roadio: '0',
            engine: '1',
            image_id: '',
            podNum: '1',
            imageMapSlave: await getAllImages({ imageType: 'notebook', visibility: '0', engine: '1' })
          }
        ]
        this.addForm = JSON.parse(JSON.stringify(this.addForm))
      }
    },
    delSlave(i) {
      this.addForm.slave_list.splice(i, 1);
    },
    async addSlave() {
      this.addForm.slave_list.push({
        product_id: '',
        image_roadio: '0',
        engine: '1',
        image_id: '',
        podNum: '1',
        imageMapSlave: await getAllImages({ imageType: 'notebook', visibility: '0', engine: '1' })
      })
    },
    async submitReject() {
      this.$refs['form'].validate(async (valid, err) => {
        if (valid) {

          if (this.$route.query.canvas_id) {
            await putCanvas(this.addForm)
            this.$router.push({
              path: '/dag',
              query: {
                id: this.$route.query.id
              }
            })
          } else {
            let vRes = await addCanvas(this.addForm)
            console.log(vRes)
            this.$router.push({
              path: '/dag',
              query: {
                id: this.$route.query.id
              }
            })
          }
          // this.$router.go(-1)
        } else {
          console.log('error submit!!', err);
          return false;
        }
      })
    },
    reset() {
      this.addForm = JSON.parse(this.resetAddForm)
    },
    async getData() {
      await this.getProducts(true)
      // await this.getSlaveProducts('noClear')
      if (this.$route.query.canvas_id) {

        let res = await getCanvasDetail({ id: this.$route.query.canvas_id })
        this.addForm = res.data
        if (this.addForm.image) {
          this.addForm.image_roadio = this.addForm.image.visibility
          this.addForm.engine = this.addForm.image.engine
        }
        this.todoName = "配置"
        await this.getImages('isUserHandle', 'noClear')
      }
      else {
        this.$set(this.addForm, 'port_list', [{ key: '10000' }])
        await this.getImages('isUserHandle', 'noClear')
      }
    },
    extendPortHandler(e) {
      console.log('e', e)
      let _image = this.imageMap.find(item => item.id == e)
      if (_image && _image.port) {
        this.addForm.port = _image.port
      }
    },
    addPort() {
      console.log('this.', this.addForm)
      this.addForm.port_list.push({ key: '' })
    },
    deletItme(tag) {
      this.addForm.port_list.splice(this.addForm.port_list.indexOf(tag), 1)
      console.log('that.', this.addForm)
    }
  },
  async mounted() {
    await this.getData()
    this.resetAddForm = JSON.stringify(this.addForm)
  },
  destroyed() {
    sessionStorage.removeItem('taskParent')
  }
}
</script>
<style lang="less" scoped>
.user-defined {
  padding-top: 16px;
}

.long-input {
  width: 100%;
}

.btns {
  padding-top: 24px;
}

.slave-btns {
  text-align: right;
  padding-bottom: 20px;
}
</style>
